<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩统计分析系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background-color: #2c3e50;
            color: white;
            padding: 1rem 0;
            text-align: center;
            margin-bottom: 2rem;
            border-radius: 5px;
        }
        
        .card {
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 10px;
        }
        
        button:hover {
            background-color: #2980b9;
        }
        
        .btn-danger {
            background-color: #e74c3c;
        }
        
        .btn-danger:hover {
            background-color: #c0392b;
        }
        
        .btn-success {
            background-color: #2ecc71;
        }
        
        .btn-success:hover {
            background-color: #27ae60;
        }
        
        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }
        
        .table-container {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        
        tr:hover {
            background-color: #f5f5f5;
        }
        
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid transparent;
            border-radius: 4px;
        }
        
        .alert-success {
            color: #155724;
            background-color: #d4edda;
            border-color: #c3e6cb;
        }
        
        .alert-danger {
            color: #721c24;
            background-color: #f8d7da;
            border-color: #f5c6cb;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .loading.show {
            display: block;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
        }
        
        .tab.active {
            border-bottom-color: #3498db;
            color: #3498db;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>成绩统计分析系统</h1>
        </header>
        
        <div id="alert-container"></div>
        
        <div class="card">
            <h2>统计分析操作</h2>
            <div class="form-group">
                <label for="xueQe">学期</label>
                <input type="text" id="xueQe" placeholder="例如：2023-2024-1">
            </div>
            <div class="form-group">
                <button onclick="executeAllStatistics()" class="btn-success">执行所有统计分析</button>
                <button onclick="clearAllStatistics()" class="btn-danger">清空所有统计数据</button>
                <!-- 导入成绩 -->
                <input type="file" id="import-file" accept=".xlsx" style="display:inline-block;margin-left:10px;">
                <button onclick="importScores()">导入成绩</button>
                <button onclick="downloadImportTemplate()">下载导入模板</button>
            </div>
        </div>
        <div class="card" id="import-result-card" style="display:none;margin-top:10px;">
            <h2>导入结果</h2>
            <div id="import-summary" class="form-group"></div>
            <div class="table-container">
                <table id="import-failures-table">
                    <thead>
                        <tr><th>行号</th><th>原因</th></tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
        
        <div class="tabs">
            <div class="tab active" onclick="switchTab('training-level')">按培养层次统计</div>
            <div class="tab" onclick="switchTab('training-level-major')">按培养层次-专业统计</div>
            <div class="tab" onclick="switchTab('training-level-major-team')">按培养层次-专业-队别统计</div>
            <div class="tab" onclick="switchTab('training-level-major-team-course')">按培养层次-专业-队别-课程统计</div>
            <div class="tab" onclick="switchTab('course')">按课程统计</div>
            <div class="tab" onclick="switchTab('course-gap')">课程间成绩差距分析</div>
        </div>
        
        <div id="training-level" class="tab-content active">
            <div class="card">
                <h2>按培养层次统计</h2>
                <div class="form-group">
                    <label for="tl-xueQe">学期（可选）</label>
                    <input type="text" id="tl-xueQe" placeholder="例如：2023-2024-1">
                </div>
                    <div class="form-group">
                        <button onclick="queryTrainingLevelStatistics()">查询统计数据</button>
                        <button onclick="executeTrainingLevelStatistics()" class="btn-success">执行统计</button>
                        <button onclick="exportStatistics()">导出</button>
                    </div>
                <div class="loading" id="tl-loading">加载中...</div>
                <div class="table-container">
                    <table id="tl-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>培养层次</th>
                                <th>总人数</th>
                                <th>形成性平均分</th>
                                <th>形成性优秀率</th>
                                <th>形成性不及格率</th>
                                <th>终结性平均分</th>
                                <th>终结性优秀率</th>
                                <th>终结性不及格率</th>
                                <th>总评平均分</th>
                                <th>总评优秀率</th>
                                <th>总评不及格率</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div id="training-level-major" class="tab-content">
            <div class="card">
                <h2>按培养层次-专业统计</h2>
                <div class="form-group">
                    <label for="tlm-xueQe">学期（可选）</label>
                    <input type="text" id="tlm-xueQe" placeholder="例如：2023-2024-1">
                </div>
                <div class="form-group">
                    <label for="tlm-peiYangCengCi">培养层次（可选）</label>
                    <input type="text" id="tlm-peiYangCengCi" placeholder="例如：本科">
                </div>
                <div class="form-group">
                    <button onclick="queryTrainingLevelMajorStatistics()">查询统计数据</button>
                    <button onclick="executeTrainingLevelMajorStatistics()" class="btn-success">执行统计</button>
                    <button onclick="exportStatistics()">导出</button>
                </div>
                <div class="loading" id="tlm-loading">加载中...</div>
                <div class="table-container">
                    <table id="tlm-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>培养层次</th>
                                <th>专业</th>
                                <th>总人数</th>
                                <th>形成性平均分</th>
                                <th>形成性优秀率</th>
                                <th>形成性不及格率</th>
                                <th>终结性平均分</th>
                                <th>终结性优秀率</th>
                                <th>终结性不及格率</th>
                                <th>总评平均分</th>
                                <th>总评优秀率</th>
                                <th>总评不及格率</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div id="training-level-major-team" class="tab-content">
            <div class="card">
                <h2>按培养层次-专业-队别统计</h2>
                <div class="form-group">
                    <label for="tlmt-xueQe">学期（可选）</label>
                    <input type="text" id="tlmt-xueQe" placeholder="例如：2023-2024-1">
                </div>
                <div class="form-group">
                    <label for="tlmt-peiYangCengCi">培养层次（可选）</label>
                    <input type="text" id="tlmt-peiYangCengCi" placeholder="例如：本科">
                </div>
                <div class="form-group">
                    <label for="tlmt-zhuanYe">专业（可选）</label>
                    <input type="text" id="tlmt-zhuanYe" placeholder="例如：计算机科学与技术">
                </div>
                <div class="form-group">
                    <button onclick="queryTrainingLevelMajorTeamStatistics()">查询统计数据</button>
                    <button onclick="executeTrainingLevelMajorTeamStatistics()" class="btn-success">执行统计</button>
                    <button onclick="exportStatistics()">导出</button>
                </div>
                <div class="loading" id="tlmt-loading">加载中...</div>
                <div class="table-container">
                    <table id="tlmt-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>培养层次</th>
                                <th>专业</th>
                                <th>队别</th>
                                <th>总人数</th>
                                <th>形成性平均分</th>
                                <th>形成性优秀率</th>
                                <th>形成性不及格率</th>
                                <th>终结性平均分</th>
                                <th>终结性优秀率</th>
                                <th>终结性不及格率</th>
                                <th>总评平均分</th>
                                <th>总评优秀率</th>
                                <th>总评不及格率</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div id="training-level-major-team-course" class="tab-content">
            <div class="card">
                <h2>按培养层次-专业-队别-课程统计</h2>
                <div class="form-group">
                    <label for="tltmc-xueQe">学期（可选）</label>
                    <input type="text" id="tltmc-xueQe" placeholder="例如：2023-2024-1">
                </div>
                <div class="form-group">
                    <button onclick="queryTrainingLevelMajorTeamCourseStatistics()">查询统计数据</button>
                    <button onclick="executeTrainingLevelMajorTeamCourseStatistics()" class="btn-success">执行统计</button>
                    <button onclick="exportStatistics()">导出</button>
                </div>
                <div class="loading" id="tltmc-loading">加载中...</div>
                <div class="table-container">
                    <table id="tltmc-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>培养层次</th>
                                <th>专业</th>
                                <th>队别</th>
                                <th>课程代码</th>
                                <th>课程名称</th>
                                <th>总人数</th>
                                <th>形成性平均分</th>
                                <th>形成性优秀率</th>
                                <th>形成性不及格率</th>
                                <th>终结性平均分</th>
                                <th>终结性优秀率</th>
                                <th>终结性不及格率</th>
                                <th>总评平均分</th>
                                <th>总评优秀率</th>
                                <th>总评不及格率</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div id="course" class="tab-content">
            <div class="card">
                <h2>按课程统计</h2>
                <div class="form-group">
                    <label for="c-xueQe">学期（可选）</label>
                    <input type="text" id="c-xueQe" placeholder="例如：2023-2024-1">
                </div>
                <div class="form-group">
                    <label for="c-courseCode">课程代码（可选）</label>
                    <input type="text" id="c-courseCode" placeholder="例如：CS101">
                </div>
                <div class="form-group">
                    <button onclick="queryCourseStatistics()">查询统计数据</button>
                    <button onclick="executeCourseStatistics()" class="btn-success">执行统计</button>
                    <button onclick="exportStatistics()">导出</button>
                </div>
                <div class="loading" id="c-loading">加载中...</div>
                <div class="table-container">
                    <table id="c-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>课程代码</th>
                                <th>课程名称</th>
                                <th>课程类型</th>
                                <th>考试类型</th>
                                <th>总人数</th>
                                <th>形成性平均分</th>
                                <th>形成性优秀率</th>
                                <th>形成性不及格率</th>
                                <th>终结性平均分</th>
                                <th>终结性优秀率</th>
                                <th>终结性不及格率</th>
                                <th>总评平均分</th>
                                <th>总评优秀率</th>
                                <th>总评不及格率</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <div id="course-gap" class="tab-content">
            <div class="card">
                <h2>课程间成绩差距分析</h2>
                <div class="form-group">
                    <label for="cg-xueQe">学期（可选）</label>
                    <input type="text" id="cg-xueQe" placeholder="例如：2023-2024-1">
                </div>
                <div class="form-group">
                    <button onclick="queryCourseGapAnalysis()">查询分析数据</button>
                    <button onclick="executeCourseGapAnalysis()" class="btn-success">执行分析</button>
                    <button onclick="exportStatistics()">导出</button>
                </div>
                <div class="loading" id="cg-loading">加载中...</div>
                <div class="table-container">
                    <table id="cg-table">
                        <thead>
                            <tr>
                                <th>学期</th>
                                <th>课程代码</th>
                                <th>课程名称</th>
                                <th>总评平均差距</th>
                                <th>总评最大差距</th>
                                <th>总评最小差距</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
        
    </div>

    <script>
        const API_BASE = '/api/statistics';
        
        // 显示提示信息
        function showAlert(message, type = 'success') {
            const alertContainer = document.getElementById('alert-container');
            const alert = document.createElement('div');
            alert.className = `alert alert-${type}`;
            alert.textContent = message;
            alertContainer.appendChild(alert);
            
            setTimeout(() => {
                alert.remove();
            }, 3000);
        }
        
        // 切换标签页
        function switchTab(tabId, element) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });

            // 移除所有标签的激活状态
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 显示选中的标签内容
            document.getElementById(tabId).classList.add('active');

            // 激活选中的标签
            if (element) element.classList.add('active');
        }
        
        // 执行所有统计分析
        async function executeAllStatistics() {
            const xueQe = document.getElementById('xueQe').value;
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute-all`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 清空所有统计数据
        async function clearAllStatistics() {
            if (!confirm('确定要清空所有统计数据吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/clear-all`, {
                    method: 'POST'
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('清空失败: ' + error.message, 'danger');
            }
        }
        
        // 查询按培养层次统计
        async function queryTrainingLevelStatistics() {
            const loading = document.getElementById('tl-loading');
            const table = document.getElementById('tl-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('tl-xueQe').value;
                const url = xueQe ? `${API_BASE}/training-level?xueQe=${encodeURIComponent(xueQe)}` : `${API_BASE}/training-level`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.peiYangCengCi || '';
                        row.insertCell(2).textContent = item.totalCount || 0;
                        row.insertCell(3).textContent = item.xcxAverage?.toFixed(3) || '';
                        row.insertCell(4).textContent = (item.xcxExcellentRate != null) ? item.xcxExcellentRate.toFixed(3) : '';
                        row.insertCell(5).textContent = (item.xcxFailRate != null) ? item.xcxFailRate.toFixed(3) : '';
                        row.insertCell(6).textContent = item.zjxAverage?.toFixed(3) || '';
                        row.insertCell(7).textContent = (item.zjxExcellentRate != null) ? item.zjxExcellentRate.toFixed(3) : '';
                        row.insertCell(8).textContent = (item.zjxFailRate != null) ? item.zjxFailRate.toFixed(3) : '';
                        row.insertCell(9).textContent = item.zpAverage?.toFixed(3) || '';
                        row.insertCell(10).textContent = (item.zpExcellentRate != null) ? item.zpExcellentRate.toFixed(3) : '';
                        row.insertCell(11).textContent = (item.zpFailRate != null) ? item.zpFailRate.toFixed(3) : '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行按培养层次统计
        async function executeTrainingLevelStatistics() {
            const xueQe = document.getElementById('tl-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeTrainingLevelStatistics xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/training-level`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 查询按培养层次-专业统计
        async function queryTrainingLevelMajorStatistics() {
            const loading = document.getElementById('tlm-loading');
            const table = document.getElementById('tlm-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('tlm-xueQe').value;
                const peiYangCengCi = document.getElementById('tlm-peiYangCengCi').value;
                let url = `${API_BASE}/training-level-major?`;
                if (xueQe) url += `xueQe=${encodeURIComponent(xueQe)}&`;
                if (peiYangCengCi) url += `peiYangCengCi=${encodeURIComponent(peiYangCengCi)}&`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.peiYangCengCi || '';
                        row.insertCell(2).textContent = item.zhuanYe || '';
                        row.insertCell(3).textContent = item.totalCount || 0;
                        row.insertCell(4).textContent = item.xcxAverage?.toFixed(3) || '';
                        row.insertCell(5).textContent = (item.xcxExcellentRate != null) ? item.xcxExcellentRate.toFixed(3) : '';
                        row.insertCell(6).textContent = (item.xcxFailRate != null) ? item.xcxFailRate.toFixed(3) : '';
                        row.insertCell(7).textContent = item.zjxAverage?.toFixed(3) || '';
                        row.insertCell(8).textContent = (item.zjxExcellentRate != null) ? item.zjxExcellentRate.toFixed(3) : '';
                        row.insertCell(9).textContent = (item.zjxFailRate != null) ? item.zjxFailRate.toFixed(3) : '';
                        row.insertCell(10).textContent = item.zpAverage?.toFixed(3) || '';
                        row.insertCell(11).textContent = (item.zpExcellentRate != null) ? item.zpExcellentRate.toFixed(3) : '';
                        row.insertCell(12).textContent = (item.zpFailRate != null) ? item.zpFailRate.toFixed(3) : '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行按培养层次-专业统计
        async function executeTrainingLevelMajorStatistics() {
            const xueQe = document.getElementById('tlm-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeTrainingLevelMajorStatistics xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/training-level-major`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 查询按培养层次-专业-队别统计
        async function queryTrainingLevelMajorTeamStatistics() {
            const loading = document.getElementById('tlmt-loading');
            const table = document.getElementById('tlmt-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('tlmt-xueQe').value;
                const peiYangCengCi = document.getElementById('tlmt-peiYangCengCi').value;
                const zhuanYe = document.getElementById('tlmt-zhuanYe').value;
                let url = `${API_BASE}/training-level-major-team?`;
                if (xueQe) url += `xueQe=${encodeURIComponent(xueQe)}&`;
                if (peiYangCengCi) url += `peiYangCengCi=${encodeURIComponent(peiYangCengCi)}&`;
                if (zhuanYe) url += `zhuanYe=${encodeURIComponent(zhuanYe)}&`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.peiYangCengCi || '';
                        row.insertCell(2).textContent = item.zhuanYe || '';
                        row.insertCell(3).textContent = item.duiBie || '';
                        row.insertCell(4).textContent = item.totalCount || 0;
                        row.insertCell(5).textContent = item.xcxAverage?.toFixed(3) || '';
                        row.insertCell(6).textContent = (item.xcxExcellentRate != null) ? item.xcxExcellentRate.toFixed(3) : '';
                        row.insertCell(7).textContent = (item.xcxFailRate != null) ? item.xcxFailRate.toFixed(3) : '';
                        row.insertCell(8).textContent = item.zjxAverage?.toFixed(3) || '';
                        row.insertCell(9).textContent = (item.zjxExcellentRate != null) ? item.zjxExcellentRate.toFixed(3) : '';
                        row.insertCell(10).textContent = (item.zjxFailRate != null) ? item.zjxFailRate.toFixed(3) : '';
                        row.insertCell(11).textContent = item.zpAverage?.toFixed(3) || '';
                        row.insertCell(12).textContent = (item.zpExcellentRate != null) ? item.zpExcellentRate.toFixed(3) : '';
                        row.insertCell(13).textContent = (item.zpFailRate != null) ? item.zpFailRate.toFixed(3) : '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行按培养层次-专业-队别统计
        async function executeTrainingLevelMajorTeamStatistics() {
            const xueQe = document.getElementById('tlmt-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeTrainingLevelMajorTeamStatistics xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/training-level-major-team`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 查询按培养层次-专业-队别-课程统计
        async function queryTrainingLevelMajorTeamCourseStatistics() {
            const loading = document.getElementById('tltmc-loading');
            const table = document.getElementById('tltmc-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('tltmc-xueQe').value;
                const url = xueQe ? `${API_BASE}/training-level-major-team-course?xueQe=${encodeURIComponent(xueQe)}` : `${API_BASE}/training-level-major-team-course`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.peiYangCengCi || '';
                        row.insertCell(2).textContent = item.zhuanYe || '';
                        row.insertCell(3).textContent = item.duiBie || '';
                        row.insertCell(4).textContent = item.courseCode || '';
                        row.insertCell(5).textContent = item.courseName || '';
                        row.insertCell(6).textContent = item.courseType || '';
                        row.insertCell(7).textContent = item.totalCount || 0;
                        row.insertCell(8).textContent = item.xcxAverage?.toFixed(3) || '';
                        row.insertCell(9).textContent = item.zjxAverage?.toFixed(3) || '';
                        row.insertCell(10).textContent = item.zpAverage?.toFixed(3) || '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行按培养层次-专业-队别-课程统计
        async function executeTrainingLevelMajorTeamCourseStatistics() {
            const xueQe = document.getElementById('tltmc-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeTrainingLevelMajorTeamCourseStatistics xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/training-level-major-team-course`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 查询按课程统计
        async function queryCourseStatistics() {
            const loading = document.getElementById('c-loading');
            const table = document.getElementById('c-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('c-xueQe').value;
                const courseCode = document.getElementById('c-courseCode').value;
                let url = `${API_BASE}/course?`;
                if (xueQe) url += `xueQe=${encodeURIComponent(xueQe)}&`;
                if (courseCode) url += `courseCode=${encodeURIComponent(courseCode)}&`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.courseCode || '';
                        row.insertCell(2).textContent = item.courseName || '';
                        row.insertCell(3).textContent = item.courseType || '';
                        row.insertCell(4).textContent = item.totalCount || 0;
                        row.insertCell(5).textContent = item.xcxAverage?.toFixed(3) || '';
                        row.insertCell(6).textContent = (item.xcxExcellentRate != null) ? item.xcxExcellentRate.toFixed(3) : '';
                        row.insertCell(7).textContent = (item.xcxFailRate != null) ? item.xcxFailRate.toFixed(3) : '';
                        row.insertCell(8).textContent = item.zjxAverage?.toFixed(3) || '';
                        row.insertCell(9).textContent = (item.zjxExcellentRate != null) ? item.zjxExcellentRate.toFixed(3) : '';
                        row.insertCell(10).textContent = (item.zjxFailRate != null) ? item.zjxFailRate.toFixed(3) : '';
                        row.insertCell(11).textContent = item.zpAverage?.toFixed(3) || '';
                        row.insertCell(12).textContent = (item.zpExcellentRate != null) ? item.zpExcellentRate.toFixed(3) : '';
                        row.insertCell(13).textContent = (item.zpFailRate != null) ? item.zpFailRate.toFixed(3) : '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行按课程统计
        async function executeCourseStatistics() {
            const xueQe = document.getElementById('c-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeCourseStatistics xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/course`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }
        
        // 查询课程间成绩差距分析
        async function queryCourseGapAnalysis() {
            const loading = document.getElementById('cg-loading');
            const table = document.getElementById('cg-table');
            const tbody = table.querySelector('tbody');
            
            loading.classList.add('show');
            tbody.innerHTML = '';
            
            try {
                const xueQe = document.getElementById('cg-xueQe').value;
                const url = xueQe ? `${API_BASE}/course-gap?xueQe=${encodeURIComponent(xueQe)}` : `${API_BASE}/course-gap`;
                
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    result.data.forEach(item => {
                        const row = tbody.insertRow();
                        row.insertCell(0).textContent = item.xueQe || '';
                        row.insertCell(1).textContent = item.courseCode || '';
                        row.insertCell(2).textContent = item.courseName || '';
                        row.insertCell(3).textContent = item.xcxGapAverage?.toFixed(3) || '';
                        row.insertCell(4).textContent = (item.xcxExcellentRateGap != null) ? item.xcxExcellentRateGap.toFixed(3) : '';
                        row.insertCell(5).textContent = (item.xcxFailRateGap != null) ? item.xcxFailRateGap.toFixed(3) : '';
                        row.insertCell(6).textContent = item.teamCount != null ? item.teamCount : '';
                        row.insertCell(7).textContent = item.zjxGapAverage?.toFixed(3) || '';
                        row.insertCell(8).textContent = (item.zjxExcellentRateGap != null) ? item.zjxExcellentRateGap.toFixed(3) : '';
                        row.insertCell(9).textContent = (item.zjxFailRateGap != null) ? item.zjxFailRateGap.toFixed(3) : '';
                        row.insertCell(10).textContent = item.teamCount != null ? item.teamCount : '';
                        row.insertCell(11).textContent = item.zpGapAverage?.toFixed(3) || '';
                        row.insertCell(12).textContent = (item.zpExcellentRateGap != null) ? item.zpExcellentRateGap.toFixed(3) : '';
                        row.insertCell(13).textContent = (item.zpFailRateGap != null) ? item.zpFailRateGap.toFixed(3) : '';
                        row.insertCell(14).textContent = item.teamCount != null ? item.teamCount : '';
                    });
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('查询失败: ' + error.message, 'danger');
            } finally {
                loading.classList.remove('show');
            }
        }
        
        // 执行课程间成绩差距分析
        async function executeCourseGapAnalysis() {
            const xueQe = document.getElementById('cg-xueQe').value || document.getElementById('xueQe').value;
            console.log('executeCourseGapAnalysis xueQe=', xueQe);
            if (!xueQe) {
                showAlert('请输入学期', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`${API_BASE}/execute/course-gap`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ xueQe })
                });
                
                const result = await response.json();
                if (result.code === 200) {
                    showAlert(result.message);
                } else {
                    showAlert(result.message, 'danger');
                }
            } catch (error) {
                showAlert('执行失败: ' + error.message, 'danger');
            }
        }

        // 导入成绩（前端）
        async function importScores() {
            const fileInput = document.getElementById('import-file');
            if (!fileInput || !fileInput.files || fileInput.files.length === 0) {
                showAlert('请选择要导入的 Excel 文件', 'danger');
                return;
            }
            const file = fileInput.files[0];
            const form = new FormData();
            form.append('file', file);

            try {
                const resp = await fetch(`${API_BASE}/import`, {
                    method: 'POST',
                    body: form
                });
                const result = await resp.json();
                if (result.code === 200) {
                    showAlert(result.message);
                    // 如果返回了详细结果，显示在页面
                    if (result.data) {
                        const data = result.data;
                        document.getElementById('import-result-card').style.display = 'block';
                        document.getElementById('import-summary').textContent = `总行数: ${data.totalRows}，已导入: ${data.imported}，失败: ${data.failures ? data.failures.length : 0}`;
                        const tbody = document.querySelector('#import-failures-table tbody');
                        tbody.innerHTML = '';
                        if (data.failures && data.failures.length > 0) {
                            data.failures.forEach(f => {
                                const tr = document.createElement('tr');
                                const tdRow = document.createElement('td'); tdRow.textContent = f.row; tr.appendChild(tdRow);
                                const tdReason = document.createElement('td'); tdReason.textContent = f.reason; tr.appendChild(tdReason);
                                tbody.appendChild(tr);
                            });
                        }
                    }
                } else {
                    showAlert(result.message || '导入失败', 'danger');
                }
            } catch (err) {
                showAlert('导入失败: ' + err.message, 'danger');
            }
        }

        // 下载导入模板
        async function downloadImportTemplate() {
            try {
                const resp = await fetch(`${API_BASE}/import/template`);
                if (!resp.ok) { showAlert('下载模板失败', 'danger'); return; }
                const blob = await resp.blob();
                const disposition = resp.headers.get('Content-Disposition') || '';
                let filename = 'score_import_template.xlsx';
                const match = /filename\*?=UTF-8''(.+)$/.exec(disposition);
                if (match && match[1]) filename = decodeURIComponent(match[1]);
                const link = document.createElement('a');
                const urlBlob = window.URL.createObjectURL(blob);
                link.href = urlBlob;
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                link.remove();
                window.URL.revokeObjectURL(urlBlob);
            } catch (e) {
                showAlert('下载模板失败: ' + e.message, 'danger');
            }
        }
        
        // 查询课程考核相关性分析
        
        
        // 执行课程考核相关性分析
        

        // 导出当前统计数据为 Excel
        async function exportStatistics() {
            const xueQe = document.getElementById('xueQe').value;
            let url = `${API_BASE}/export`;
            if (xueQe) url += `?xueQe=${encodeURIComponent(xueQe)}`;

            try {
                const response = await fetch(url);
                if (!response.ok) {
                    showAlert('导出失败', 'danger');
                    return;
                }

                const blob = await response.blob();
                const disposition = response.headers.get('Content-Disposition') || '';
                let filename = 'statistics.xlsx';
                const match = /filename\*?=UTF-8''(.+)$/.exec(disposition);
                if (match && match[1]) {
                    filename = decodeURIComponent(match[1]);
                }

                const link = document.createElement('a');
                const urlBlob = window.URL.createObjectURL(blob);
                link.href = urlBlob;
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                link.remove();
                window.URL.revokeObjectURL(urlBlob);
            } catch (error) {
                showAlert('导出失败: ' + error.message, 'danger');
            }
        }
    </script>
</body>
</html>